package com.lzm.flash;

import android.os.Bundle;
import android.os.Message;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import static com.lzm.flash.Type.*;

/**
 * Created by lzm on 2018/2/25.
 * 接受广播消息的线程
 */

class BroadcastRecvThread implements Runnable {
    private DatagramSocket  m_socket;
    private  MainActivity.MainHandler m_myHandler;

    BroadcastRecvThread(MainActivity.MainHandler handler)
    {
        super();
        m_myHandler=handler;
    }
    private boolean initSocket()
    {
        try {
            m_socket=new DatagramSocket(42000);
        } catch (SocketException e) {
            e.printStackTrace();
            return false;
        }
        return  true;
    }
    @Override
    public void run() {
        if (!initSocket())
        {
            Message msg=m_myHandler.obtainMessage();
            Bundle msgData=new Bundle();
            msgData.putInt("msg_type", recv_broadcast_err);
            msgData.putString("data","广播socket 发生异常  初始化失败");
            msg.setData(msgData);
            m_myHandler.sendMessage(msg);
            return;
        }

        while (true)
        {
            byte[] receMsgs=new byte[2048];
            DatagramPacket dp=new DatagramPacket(receMsgs,receMsgs.length);
            try {
                m_socket.receive(dp);
                Message msg = m_myHandler.obtainMessage();
                Bundle msgData = new Bundle();
                Bundle dataMap= new Bundle();
                String json=new String(dp.getData(),0,dp.getLength());
                JSONObject jsonObj=new JSONObject(json);
                dataMap.putString("name",jsonObj.getString("name"));
                dataMap.putString("ip", String.valueOf(dp.getSocketAddress()));
                dataMap.putString("mac",jsonObj.getString("mac"));
                msgData.putInt("msg_type", recv_broadcast);
                msgData.putBundle("data",dataMap);
                msg.setData(msgData);
                m_myHandler.sendMessage(msg);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}






















